package com.ia.aistream.common.utils.spring;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author chenjunsheng
 */
@Component
public final class SpringContext implements ApplicationContextAware {
    /**
     * 应用上下文
     */
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContext.applicationContext = applicationContext;
    }

    /**
     * 获取 Spring 容器管理的 bean 对象
     *
     * @param clazz 类型对象
     * @return spring 容器中的实例对象
     * @author: chenjunsheng
     */
    public static <T> T getBean(Class<T> clazz) {
        if (SpringContext.applicationContext == null) {
            return null;
        }
        return applicationContext.getBean(clazz);
    }

    /**
     * 根据bean名称获取Spring管理的bean对象
     *
     * @param beanName 自定义bean的名称
     * @param clazz    类型对象
     * @return spring 容器中的实例对象
     * @author: chenjunsheng
     */
    public static <T> T getBean(String beanName, Class<T> clazz) {
        if (applicationContext == null) {
            return null;
        }
        return applicationContext.getBean(beanName, clazz);
    }
}
